package com.alex.seo.service.logging;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alex.seo.dao.log.LogDao;
import com.alex.seo.domain.log.Log;

@Transactional
public class LoggingServiceBean implements LoggingService {

	private LogDao logDao;

	@Required
	public void setLogDao(LogDao logDao) {
		this.logDao = logDao;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void logError(Throwable t) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		PrintWriter writer = new PrintWriter(out);
		t.printStackTrace(writer);
		writer.close();
		String message = new String(out.toByteArray());
		logDao.persist(new Log(LogType.GENERAL_ERROR, message));
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void logError(String message) {
		logDao.persist(new Log(LogType.GENERAL_ERROR, message));
	}

	@Override
	public void logEvent(LogType type, String message) {
		logDao.persist(new Log(type, message));
	}

}
